import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Listener implements Runnable {

	private Sender sender;
	private Ticker ticker;
	private int port;

	public Listener(int port, Sender sender, Ticker ticker) {
		this.sender = sender;
		this.port = port;
		this.ticker = ticker;
	}

	public void run() {
		try {
			startListener(port);
		} catch (IOException e) {
			System.out.println("couldn't start listening on port " + port + ": " + e);
		}
	}

	private void startListener(int port) throws IOException {
		ServerSocket anschluss = new ServerSocket(port);
		BufferedReader Eingabe;
		StringBuilder stringb;
		while (true) {
			Socket lauschen = anschluss.accept();
			InputStreamReader PortLeser = new InputStreamReader(lauschen.getInputStream());
			Eingabe = new BufferedReader(PortLeser);
			stringb = new StringBuilder(Eingabe.readLine());
			System.out.println("the listener received: " + stringb.toString());
			if (stringb.indexOf("command:") == 0) process(stringb);
		}
	}

	private void process(StringBuilder stringb) {
		try {
			if (stringb.length() < 16) {
				return;
			}
			else if (stringb.substring(8, 16).equals("setPort:")) {
				setPort(Integer.valueOf(stringb.substring(16)).intValue());
			}
			else if (stringb.substring(8, 20).equals("setInterval:")) {
				ticker.setInterval(Integer.valueOf(stringb.substring(20)).intValue());
			}
			else if (stringb.substring(8, 21).toString().equals("setRecipient:")) {
				setRecipient(stringb.substring(21));
			}
		} catch (StringIndexOutOfBoundsException e) {
			System.out.println("string received is shorter than shortest command");
		}
	}

	private void setRecipient(String recipient) {
		sender.setRecipient(recipient);
		System.out.println("recipient is now:" + recipient);
	}

	private void setPort(int port) {
		if (port < 1 || port > 65535) return;
		sender.setLocalSendingPort(port);
		System.out.println("port is now: " + port);
	}

}